let id = ''
const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
var tapC = true;

Page({
  data: {
    project: [],
    active: 0,
    havePub: false,
    pubEnd: false,
    haveAdmit: false,
    vlnListHasAdmit: [] //报名了已录取的用户列表
  },
  onLoad(e) {
    console.log(e.id)
    console.log("openid", App.globalData.openid)
    console.log("11", App.globalData.userInfo)
    this.setData({
      projectId: e.id,
    })
    this.getVlnListNotAdmit() //获取报名的用户列表

    wx.cloud.database().collection("project").doc(e.id)
      .get()
      .then(res => {
        console.log("查询该项目信息", res)
        console.log("查询成功报名截止日期最后一刻的时间戳", res.data.signEndDateStamp)
        let startYear = new Date(res.data.startDateStamp).getFullYear()
        let startMonth = new Date(res.data.startDateStamp).getMonth() + 1
        let startDate = new Date(res.data.startDateStamp).getDate()
        let endYear = new Date(res.data.endDateStamp).getFullYear()
        let endMonth = new Date(res.data.endDateStamp).getMonth() + 1
        let endDate = new Date(res.data.endDateStamp).getDate()
        this.setData({
          project: res.data,
          startYear: startYear,
          startMonth: startMonth,
          startDate: startDate,
          endYear: endYear,
          endMonth: endMonth,
          endDate: endDate,
          startTime: res.data.startTime,
          endTime: res.data.endTime,
          signEndDateStamp: res.data.signEndDateStamp,
        })
        this.judgePubEnd()
      })
      .catch(res => {
        console.log("查询失败", res)
      })

    // console.log(getApp().globalData)


    // let time=new Date(this.data.project[0].endDateStamp)
    // console.log(time)
  },
  //获取报名该项目的用户列表
  getVlnListNotAdmit() {
    db.collection("project").doc(this.data.projectId).get()
      .then(res => {
        console.log("报名该项目的用户列表", res.data.vlnListNotAdmit)
        this.setData({
          vlnListNotAdmit: res.data.vlnListNotAdmit,
          vlnListHasAdmit: res.data.vlnListHasAdmit
        })
        // 判断一下这个用户报名过了没
        if ((this.data.vlnListNotAdmit.findIndex(e => e._id == App.globalData.userInfo._id) != -1)) {
          console.log("该用户已报名")
          this.setData({
            havePub: true
          })
        } else if ((this.data.vlnListHasAdmit.findIndex(e => e.vln_id == App.globalData.userInfo._id) != -1)) {
          console.log("该用户已被录取")
          this.setData({
            haveAdmit: true
          })
        }
      }).catch(err => {
        console.log(err)
      })
  },
  //判断报名是否截止
  judgePubEnd() {
    let now = Date.parse(new Date())
    // console.log(now)
    console.log(this.data.signEndDateStamp)
    if (now > this.data.signEndDateStamp) {
      this.setData({
        pubEnd: true,
      })
    }
    if (this.data.vlnListHasAdmit.length == this.data.project.peopleNum) {
      this.setData({
        pubEnd: true,
      })
    }
  },

  //点击了报名按钮
  Sign() {
    //没过报名截止日期且没报名
    if (this.data.havePub == false && this.data.pubEnd == false) {
      wx.requestSubscribeMessage({
        tmplIds: ['6OXlbXtKhnrpQDhjf-5oqQDh7O_-eavpqnNMwK-eXm8', 'avzUeNJScbyjO9dhIJ_2_GRfl26zqiX23a00r2b03gw']
      }).then(res => {
        console.log("授权订阅消息成功", res)
        //如果点击了允许(两个同时会是accept，不会1个re 1个ac，所以只用判断一个)
        if (res['6OXlbXtKhnrpQDhjf-5oqQDh7O_-eavpqnNMwK-eXm8'] == "accept") {
          console.log("App.globalData", App.globalData)
          console.log("报名用户的openid", App.globalData.openid)
          wx.cloud.callFunction({
            name: "sendSubptMessage",
            data: {
              openId: App.globalData.openid,
              projectName: this.data.project.taskTitle,
              teamNickname: this.data.project.teamNickname,
              userName: App.globalData.userInfo.userInfo.name,
              phoneNum: this.data.project.phoneNum,
              dateTime: this.data.startYear + "年" + this.data.startMonth + "月" + this.data.startDate + "日", //时间前有个空格
              projectId:this.data.projectId,
              flag: "willSign"
            }
          }).then(res => {
            console.log("发送订阅消息云函数调用成功", res)
            //按钮变成已报名的状态
            this.setData({
              havePub: true
            })

            //把报名人的头像和名字push到该项目数据库的志愿者列表里
            console.log("报名用户的_id", App.globalData.userInfo._id)
            console.log("报名用户的头像图片链接", App.globalData.userInfo.userInfo.avaUrl)
            console.log("报名用户的名字", App.globalData.userInfo.userInfo.name)
            console.log("这个项目的id", this.data.projectId)
            db.collection('project').doc(this.data.projectId).update({
                data: {
                  vlnListNotAdmit: _.push({
                    avar: App.globalData.userInfo.userInfo.avaUrl,
                    name: App.globalData.userInfo.userInfo.name,
                    _id: App.globalData.userInfo._id,
                    openid: App.globalData.openid
                  })
                }
              }).then(res => {
                console.log("把报名人push进该项目的志愿者列表成功", res)
                this.getVlnListNotAdmit()
              })
              .catch(err => {
                console.log("把报名人push进该项目的志愿者列表失败", err)
              })

            //把该项目的信息push进志愿者的待录取列表里
            db.collection('all_user').doc(App.globalData.userInfo._id).update({
                data: {
                  will_be_admit: _.push({
                    projectName: this.data.project.taskTitle,
                    project_id: this.data.projectId
                  })
                }
              }).then(res => {
                console.log("把项目信息push入待录取数组成功", res)
              })
              .catch(err => {
                console.log("把项目信息push入待录取数组失败", err)
              })

          }).catch(err => {
            console.log("发送订阅消息云函数调用失败", err)
          })
        }
      }).catch(err => {
        console.log("授权订阅消息失败", err)
      })

    }

    //已报名且没过截止日期(点了让他取消报名)
    else if (this.data.havePub == true && this.data.pubEnd == false) {
      wx.requestSubscribeMessage({
        tmplIds: ['K9SK2TVjvPDVf4kETDriPWJH9vK608k2lk7t7IWYhh4'],
      }).then(res => {
        console.log("授权取消订阅消息成功", res['K9SK2TVjvPDVf4kETDriPWJH9vK608k2lk7t7IWYhh4'])
        let now = new Date()
        let nowYear = now.getFullYear()
        let nowMonth = now.getMonth() + 1
        let nowDate = now.getDate()
        let nowHour = now.getHours()
        let nowMinute = String(now).slice(19, 21)
        console.log(nowYear + "年" + nowMonth + "月" + nowDate + "日 " + nowHour + ":" + nowMinute)

        //如果点击了允许
        if (res['K9SK2TVjvPDVf4kETDriPWJH9vK608k2lk7t7IWYhh4'] === "accept") {
          console.log("取消报名用户的名字", App.globalData.userInfo.userInfo.name)
          wx.cloud.callFunction({
            name: "sendSubptMessage",
            data: {
              openId: App.globalData.openid,
              projectName: this.data.project.taskTitle,
              teamNickname: this.data.project.teamNickname,
              nowTime: nowYear + "年" + nowMonth + "月" + nowDate + "日 " + nowHour + ":" + nowMinute,
              userName: App.globalData.userInfo.userInfo.name,
              projectId:this.data.projectId,
              flag: "cancelSign"
            }
          }).then(res => {
            console.log("发送取消订阅消息云函数调用成功", res)
            //按钮变成未报名的状态
            this.setData({
              havePub: false
            })

            //把取消报名人从该项目的待录取数组里删除
            console.log("报名用户的_id", App.globalData.userInfo._id)
            console.log("这个项目的id", this.data.projectId)
            db.collection('project').doc(this.data.projectId).update({
                data: {
                  vlnListNotAdmit: _.pull({
                    _id: App.globalData.userInfo._id
                  })
                }
              }).then(res => {
                console.log("把取消报名人删除成功", res)
                this.getVlnListNotAdmit()
              })
              .catch(err => {
                console.log("把取消报名人删除失败", err)
              })

            //把该项目从取消报名人的待录取数组里删除
            db.collection('all_user').doc(App.globalData.userInfo._id).update({
                data: {
                  will_be_admit: _.pull({
                    project_id: this.data.projectId
                  })
                }
              }).then(res => {
                console.log("把取消的项目删除成功", res)
                this.getVlnListNotAdmit()
              })
              .catch(err => {
                console.log("把取消的项目删除失败", err)
              })
          }).catch(err => {
            console.log("发送取消订阅消息云函数调用失败", err)
          })
        }
      }).catch(err => {
        console.log("授权取消订阅消息失败", err)
      })

    }

    //没报名但已过截止日期
    else {
      this.setData({
        havePub: false
      })
      JSON.stringify(this.data.vlnListNotAdmit).indexOf(`"_id":"${App.globalData.userInfo._id}"`)
    }
  },

  onChange(e) {

    console.log(e)
    this.setData({
      active: e.detail
    });
  },
  //点击了咨询(联系)  项目对象里面没有团队头像，这个页面的团队头像在哪里？
  tapConsult() {
    //判断是否注册和登录
    const registerState = (App.globalData.userInfo.userInfo.ID==undefined) ? false :true;
    const loginState = (App.globalData.userInfo.userInfo.avaUrl==undefined) ? false :true;
    if(!registerState){
      return wx.showToast({
        title: '请先注册',
        icon:'error'
      })
    }else if(!loginState){
      return wx.showToast({
        title: '请先登录',
        icon:'error'
      })
    }
    console.log('tapC',tapC);
    if(tapC==false) return;
    tapC = false;
    //改前： var id = this.data.project._id;//项目id
    //改后: 加个 团队的openid
    //const teamOpenid = this.data.project.teamOpenid;
    //const openid = App.globalData.openid; //志愿者openid
    
    // 该项目的记录_id 与 该志愿者openid 确定而成的唯一会话号
    // 改前: var sid = id + openid;
    // 改后：发布该项目的团队openid 与 该志愿者openid确定而成的唯一会话号
    const project = this.data.project;
    const sid = App.globalData.openid + project.teamOpenid;
    const hisUserInfo = project.teamAvatraurl;
    const volunteer= {
      avatarUrl: App.globalData.userInfo.userInfo.avaUrl,
      nickName: App.globalData.userInfo.userInfo.name,
      openid: App.globalData.openid
    };
    const team={
      avatarUrl: project.teamAvatraurl,
      nickName: project.teamNickname,
      openid: project.teamOpenid
    }
    // 查询 该会话号是否 存在
    //this.findSession(sid);
    //改写为云函数、
    wx.cloud.callFunction({
      name:"lyc_consult",
      data:{
        type: 'newSession',
        sid:sid,
        volunteer:volunteer,
        team:team, 
      }
    })
    .then((res)=>{
      console.log('点击联系的云函数调用成功',res.result.isSid);
      if(res.result.isSid){
        wx.navigateTo({
          url: '/pages/chatManager/chatManager?session_id=' + sid + '&hisUserInfo=' + hisUserInfo,
        })
      }else{
        wx.showToast({
          title: '联系失败',
          icon:'error'
        })
      }
    })
    .catch((res)=>{
      console.log('点击联系的云函数调用失败',res);
      wx.showToast({
        title: '联系失败',
        icon:'error'
      })
    })
    .finally(()=>{tapC = true;})

  },
  

})